//
//  LoginViewModel.m
//  myfamily
//
//  Created by xiayiyong on 15/7/2.
//  Copyright © 2015年 我爱我家. All rights reserved.
//

#import "LoginViewModel.h"
#import "BaseViewModel.h"
#import "BaseHTTPManager.h"
#import "NSString+STRegex.h"
#import "LoginModel.h"

@implementation LoginViewModel

-(RACSignal *)checkPhoneSignal
{
    @weakify(self);
    return [RACObserve(self,username) map:^id(NSString *text) {
        @strongify(self);
        return @([text isValidPhone]);
    }];
}

-(RACSignal *)checkPasswordSignal
{
    @weakify(self);
    return [RACObserve(self,password) map:^id(NSString *text) {
        @strongify(self);
        return @([text isValidPhone]);
    }];
}

- (RACSignal*)checkPhonePasswordSignal
{
    RACSignal* usernameSignal = [RACObserve(self, username) distinctUntilChanged];
    RACSignal* passwordSignal = [RACObserve(self, password) distinctUntilChanged];
    
    return [RACSignal combineLatest:@[ usernameSignal, passwordSignal ]
                             reduce:^(NSString* username, NSString* password) {
                                 BOOL result = [username isValidPhone] && [password isValidPassword];
                                 return @(result);
                             }];
}

-(RACSignal *)checkInputSignal {
    @weakify(self);
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        @strongify(self);
        BOOL result = [self.username isValidPhone] && [self.password isValidPassword];
        [subscriber sendNext:@(result)];
        [subscriber sendCompleted];
        
        return [RACDisposable disposableWithBlock:^{
            NSLog(@"clean up");
        }];
    }];
}

-(RACCommand *)loginCommand
{
    @weakify(self);
    return [[RACCommand alloc]initWithSignalBlock:^RACSignal *(id input) {
        NSLog(@"按钮被点击");
        return [RACSignal empty];
    }];
}

- (RACCommand*)loginButtonCommand
{
    if (!_loginButtonCommand) {
        _loginButtonCommand = [[RACCommand alloc] initWithEnabled:[self checkPhonePasswordSignal] signalBlock:^RACSignal * (id input) {
            return [self urlResults];
        }];
    }
    
    [_loginButtonCommand.executionSignals subscribeNext:^(id x) {
        
    } error:^(NSError *error) {
        
    } completed:^{
        
    }];
    
    return _loginButtonCommand;
}

-(RACSignal *)urlResults {
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        NSError *error;
        NSString *result = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.devtang.com"]
                                                    encoding:NSUTF8StringEncoding
                                                       error:&error];
        NSLog(@"download");
        if (!result) {
            [subscriber sendError:error];
        } else {
            [subscriber sendNext:result];
            [subscriber sendCompleted];
        }
        return [RACDisposable disposableWithBlock:^{
            NSLog(@"clean up");
        }];
    }];
}

- (RACSignal *)signInSignal {
    @weakify(self);
    return [RACSignal createSignal:^RACDisposable *(id subscriber){
        @strongify(self);
        AFHTTPRequestOperation *operation =[BaseHTTPManager doTaskWithURL:@"http://121.40.35.172:8085/web/user.do"
                            parameters:@{
                                         @"action":@"login",
                                         @"phone":self.username,
                                         @"pwd":self.password
                                         }
                               complete:^(NSError *error, BaseResponse *rsp) {
                                   if (error)
                                   {
                                       [subscriber sendError:error];
                                   }
                                   else
                                   {
                                       self.data=(LoginRspModel*)rsp;
                                       [subscriber sendNext:@"yes"];
                                       [subscriber sendCompleted];
                                   }
                               }];
        
        return [RACDisposable disposableWithBlock:^{
            [operation cancel];
        }];
    }];
}

-(void)uploadData:(id)sender {
    //using with @strongify(self) this makes sure that self isn't retained in the blocks
    //this is declared int libextobjc's EXTScope.h file
    @weakify(self);
    
    [[RACScheduler scheduler] schedule:^{
        sleep(1);
        //pretend we are uploading to a server on a backround thread...
        //dont ever put sleep in your code
        //upload player & points...
        
        [[RACScheduler mainThreadScheduler] schedule:^{
            //this creates a reference to weak self ( @weakify(self); )
            //makes sure self isn't retained
            //TODO: shouldn't reference a UI element in the view model. probably need an upload signal signal
            @strongify(self);
            NSString *msg = [NSString stringWithFormat:@"Updated..."];
            
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Upload Successfull"
                                                            message:msg
                                                           delegate:nil
                                                  cancelButtonTitle:@"ok"
                                                  otherButtonTitles:nil];
            [alert show];
        }];
    }];
}

@end
